<template>
  <van-form @submit="onSubmit" v-if="editInfo" style="margin-top: 50px">
    <van-cell-group inset>
      <!-- 技能认证编辑 -->
      <div v-if="editInfo.editKey === 'skillCert'">
        <div style="margin-bottom: 16px; padding: 16px; background-color: #fff; border-radius: 8px;">
          <h3 style="margin-bottom: 12px; font-weight: 600;">技能认证信息</h3>
          <div v-for="(skill, index) in skillsList" :key="index" class="skill-item">
            <div class="skill-row">
              <van-field
                v-model="skill.name"
                :name="`skillName_${index}`"
                label="技能名称"
                placeholder="请输入技能名称（如Python、UI设计）"
                style="flex: 2;"
              />
              <van-field
                v-model="skill.level"
                :name="`skillLevel_${index}`"
                label="熟练度"
                placeholder="请输入熟练度（如入门、熟练、精通）"
                style="flex: 2; margin-left: 12px;"
              />
              <van-icon
                name="clear"
                @click="removeSkill(index)"
                style="align-self: center; margin-left: 12px; cursor: pointer;"
              />
            </div>
          </div>
          <van-button type="primary" plain @click="addSkill" style="width: 100%; margin-top: 12px;">
            添加技能
          </van-button>
        </div>
      </div>

      <!-- 时间可用性编辑 -->
      <div v-if="editInfo.editKey === 'availTime'">
        <div style="margin-bottom: 16px; padding: 16px; background-color: #fff; border-radius: 8px;">
          <h3 style="margin-bottom: 12px; font-weight: 600;">时间可用性</h3>
          <div v-for="(time, index) in timeList" :key="index" class="time-item">
            <div class="time-row">
              <van-field
                v-model="time.period"
                :name="`time_period_${index}`"
                label="时间段"
                placeholder="如：周一至周五、周末、周一"
                style="flex: 1;"
              />
              <van-field
                v-model="time.timeRange"
                :name="`time_range_${index}`"
                label="时间范围"
                placeholder="如：19:00-22:00、全天"
                style="flex: 1; margin-left: 12px;"
              />
              <van-icon
                name="clear"
                @click="removeTime(index)"
                style="align-self: center; margin-left: 12px; cursor: pointer;"
              />
            </div>
          </div>
          <van-button type="primary" plain @click="addTime" style="width: 100%; margin-top: 12px;">
            添加时间段
          </van-button>
        </div>
      </div>

      <!-- 协作偏好编辑 -->
      <div v-if="editInfo.editKey === 'collabPrefer'">
        <div style="margin-bottom: 16px; padding: 16px; background-color: #fff; border-radius: 8px;">
          <h3 style="margin-bottom: 12px; font-weight: 600;">协作偏好</h3>
          <van-field
            v-model="collabPrefer.communicationFreq"
            name="communication_freq"
            label="沟通频率"
            placeholder="如：每日1次、每周2次"
          />
          <van-field
            v-model="collabPrefer.taskAllocation"
            name="task_allocation"
            label="任务分工"
            placeholder="如：敏捷开发、瀑布模型"
          />
          <van-field
            v-model="collabPrefer.responseSpeed"
            name="response_speed"
            label="响应速度"
            placeholder="如：2小时内、当天内"
          />
          <van-field
            v-model="collabPrefer.otherPreferences"
            name="other_preferences"
            label="其他偏好（选填）"
            type="textarea"
            placeholder="请输入其他协作偏好"
            rows="3"
          />
        </div>
      </div>

      <!-- 用户类型和会员等级选择 -->
      <div v-if="editInfo.editKey === 'user_type'">
        <van-field name="user_type" label="用户类型" readonly :value="selectedUserType">
          <template #input>
            <van-picker
              show-toolbar
              title="选择用户类型"
              :columns="userTypeOptions"
              :default-index="getUserTypeIndex"
              @confirm="(value) => { selectedUserType = value }"
              @cancel="handleCancel"
            />
          </template>
        </van-field>
      </div>
    </van-cell-group>

    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {onMounted, ref, computed} from "vue";
import {userStore} from "../stores/user/user.ts";
import {showToast} from "vant";
import {updateUserInfo} from "../api/userApi.ts";

const route = useRoute();
const router = useRouter();
const userStoreAPI = userStore();

// 编辑信息
const editInfo = ref<any>(null);
// 用户信息
const user = ref<any>(null);

// 技能认证相关
const skillsList = ref<Array<{ name: string; level: string; }>>([]);
// 时间可用性相关
const timeList = ref<Array<{ period: string; timeRange: string }>>([]);
// 协作偏好相关
const collabPrefer = ref({
  communicationFreq: "",
  taskAllocation: "",
  responseSpeed: "",
  otherPreferences: ""
});
// 用户类型相关
const userTypeOptions = ['学生', '职场人', '自由职业者'];
const selectedUserType = ref('');

// 获取用户类型索引
const getUserTypeIndex = computed(() => {
  if (user.value && user.value.user_type !== undefined) {
    return user.value.user_type;
  }
  return 0;
});

// 添加技能
const addSkill = () => {
  skillsList.value.push({ name: '', level: '' });
};

// 移除技能
const removeSkill = (index: number) => {
  skillsList.value.splice(index, 1);
};

// 添加时间段
const addTime = () => {
  timeList.value.push({ period: '', timeRange: '' });
};

// 移除时间段
const removeTime = (index: number) => {
  timeList.value.splice(index, 1);
};

// 取消选择
const handleCancel = () => {
  if (user.value && user.value.user_type !== undefined) {
    selectedUserType.value = userTypeOptions[user.value.user_type];
  }
};

// 提交给后台修改信息
const onSubmit = async () => {
  // 验证必填项
  if (editInfo.value.editKey === 'skillCert') {
    const emptySkills = skillsList.value.filter(skill => !skill.name || !skill.level);
    if (emptySkills.length > 0) {
      showToast('请填写完整的技能名称和熟练度');
      return;
    }
  } else if (editInfo.value.editKey === 'availTime') {
    const emptyTimes = timeList.value.filter(time => !time.period || !time.timeRange);
    if (emptyTimes.length > 0) {
      showToast('请填写完整的时间段和时间范围');
      return;
    }
  } else if (editInfo.value.editKey === 'collabPrefer') {
    if (!collabPrefer.value.communicationFreq || !collabPrefer.value.taskAllocation || !collabPrefer.value.responseSpeed) {
      showToast('请填写沟通频率、任务分工和响应速度');
      return;
    }
  }

  // 准备提交数据
  const submitData = {
    editId: user.value.id,
    editKey: editInfo.value.editKey,
    editValue: ''
  };

  if (editInfo.value.editKey === 'skillCert') {
    submitData.editValue = JSON.stringify(skillsList.value);
  } else if (editInfo.value.editKey === 'availTime') {
    submitData.editValue = JSON.stringify(timeList.value);
  } else if (editInfo.value.editKey === 'collabPrefer') {
    submitData.editValue = JSON.stringify(collabPrefer.value);
  } else if (editInfo.value.editKey === 'user_type') {
    submitData.editValue = userTypeOptions.indexOf(selectedUserType.value);
  }

  // 提交修改
  const res = await updateUserInfo(submitData);
  if (200 === res.code) {
    // 修改成功
    showToast('修改成功');
    
    // 更新同步pinia
    const currentUser = await userStoreAPI.getCurrentUser();
    currentUser[editInfo.value.editKey] = submitData.editValue;
    userStoreAPI.setCurrentUser(currentUser);
    
    router.back();//回到用户中心
  } else {
    // 提示出错
    showToast('修改失败!');
  }
};

onMounted(async () => {
  // 获取编辑信息
  editInfo.value = {
    editKey: route.query.key
  };
  
  // 获取用户信息
  user.value = await userStoreAPI.getCurrentUser();
  
  // 初始化数据
  if (editInfo.value.editKey === 'skillCert' && user.value.skillCert) {
    try {
      skillsList.value = JSON.parse(user.value.skillCert);
      // 如果解析后为空数组，添加一个空的技能项
      if (skillsList.value.length === 0) {
        addSkill();
      }
    } catch (e) {
      addSkill();
    }
  } else if (editInfo.value.editKey === 'skillCert') {
    addSkill();
  }
  
  if (editInfo.value.editKey === 'availTime' && user.value.availTime) {
    try {
      timeList.value = JSON.parse(user.value.availTime);
      // 如果解析后为空数组，添加一个空的时间段
      if (timeList.value.length === 0) {
        addTime();
      }
    } catch (e) {
      addTime();
    }
  } else if (editInfo.value.editKey === 'availTime') {
    addTime();
  }
  
  if (editInfo.value.editKey === 'collabPrefer' && user.value.collabPrefer) {
    try {
      collabPrefer.value = JSON.parse(user.value.collabPrefer);
    } catch (e) {
      // 保留默认值
    }
  }
  
  if (editInfo.value.editKey === 'user_type' && user.value.user_type !== undefined) {
    selectedUserType.value = userTypeOptions[user.value.user_type];
  } else if (editInfo.value.editKey === 'user_type') {
    selectedUserType.value = '学生';
  }
});
</script>

<style scoped>
.skill-item,
.time-item {
  margin-bottom: 12px;
}

.skill-row,
.time-row {
  display: flex;
  align-items: center;
}

:deep(.van-field) {
  flex: 1;
}

:deep(.van-button) {
  margin-top: 12px;
}
</style>